package com.xbh.wificonfiglib.util;

import android.os.SystemClock;

import java.util.Random;

/**
 * @author: xiaoqiwen
 * Create on 2020/11/25
 * Email: Qiwen.Xiao@lango-tech.com
 */
public class SimpleCipherUtil {
    private static final short[] crcTable = new short[256];
    private static short CRC_POLYNOM = (short) (new Random().nextInt(256) & 0xff);
    private static final short CRC_INITIAL = 0x00;

    static {
        for (int dividend = 0; dividend < 256; dividend++) {
            int remainder = dividend;// << 8;
            for (int bit = 0; bit < 8; ++bit)
                if ((remainder & 0x01) != 0)
                    remainder = (remainder >>> 1) ^ CRC_POLYNOM;
                else
                    remainder >>>= 1;
            crcTable[dividend] = (short) remainder;
        }
    }

    public static short getPolyNum() {
        return CRC_POLYNOM;
    }

    /**
     * 设备端连接成功后调试此方法更新crcTable
     */
    public static void updateTable() {
        CRC_POLYNOM = (short) (new Random().nextInt(256) & 0xff);

        for (int dividend = 0; dividend < 256; dividend++) {
            int remainder = dividend;// << 8;
            for (int bit = 0; bit < 8; ++bit)
                if ((remainder & 0x01) != 0)
                    remainder = (remainder >>> 1) ^ CRC_POLYNOM;
                else
                    remainder >>>= 1;
            crcTable[dividend] = (short) remainder;
        }
    }

    public static byte[] encrypt(byte[] content) {
        byte[] bytes = new byte[content.length];
        for (int i = 0; i < content.length; i++) {
            bytes[i] = (byte) (content[i] ^ crcTable[i % crcTable.length]);
        }
        return bytes;
    }
}
